package is.xdumper.xml;

import is.xdumper.XdumperConf;
import is.xdumper.XdumperNoPathException;
import is.xdumper.type.Dump;
import java.io.*;
import java.rmi.RemoteException;
import javax.naming.NamingException;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.*;

/**
 *
 * @author aspr0
 */
public class XdumperXmlReader
{
    /* passing stream to bean caused serialization error, changed to string */
    public static Dump read(String dumpXml) throws ParserConfigurationException, SAXException, IOException,
                                                   NamingException, RemoteException, XdumperNoPathException
    {
        File schemaFile = new File(XdumperConf.getPathDumpSchema());
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setSchema(schema);

        XMLReader reader = factory.newSAXParser().getXMLReader();

        XdumperXmlHandler handler = new XdumperXmlHandler();
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);

        BufferedReader dumpXmlReader = new BufferedReader(new StringReader(dumpXml));
        InputSource source = new InputSource(dumpXmlReader);
        reader.parse(source);

        return handler.getDump();
    }
}
